#!/bin/bash

DIRECTORY="$(dirname "$(dirname "$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )")")"

function error {
  echo -e "\\e[91m$1\\e[39m"
  exit 1
}


hardware="$(cat /proc/cpuinfo)"
if [ ! -z "$(echo "$hardware" | grep ARMv7)" ];then
  hardware='pi3'
elif [ ! -z "$(echo "$hardware" | grep ARMv6)" ];then
  hardware='pi0'
else
  hardware='pi4'
fi

if [ "$hardware" == 'pi0' ];then
  error "Wine is not compatible with the Raspberry Pi Zero or other ARMv6 boards."
fi

if [ ! -e /proc/config.gz ];then
  sudo modprobe configs || exit 1
  if [ ! -e /proc/config.gz ];then
    error "/proc/config.gz does not exist after running sudo modprobe configs!"
  fi
fi

vmsplit_output="$(gunzip < /proc/config.gz | grep VMSPLIT)"
if [ -z "$vmsplit_output" ];then
  kernel="$(uname -m)"
  if [ $kernel == aarch64 ];then
    echo "No memory split information due to running a 64-bit kernel. Continuing..."
  else
    echo "No memory split information and not running a 64-bit kernel. Strange."
    sleep 2
    echo "Continuing..."
  fi
elif echo "$vmsplit_output" | grep -q "^CONFIG_VMSPLIT_2G=y" || echo "$vmsplit_output" | grep -q "^# CONFIG_VMSPLIT_3G is not set" ;then
  
  #ensure hardware is pi3 for kernel compiling to work
  if [ "$hardware" != 'pi3' ];then
    error "This script is not capable of handling your $hardware board with a 2G/2G memory split.\nWhatever you did to get yourself into this situation, undo it and try installing Wine again."
  fi
  
  #continue asking until valid answer
  while true;do
    echo -e "You are using a kernel with a 2G/2G memory split.\nWine will not work on such systems. What would you like to do?
1. Switch to the 64-bit kernel (about 2 minutes)
2. Compile a 3G/1G kernel (several hours)
3. Install a precompiled 3G/1G kernel (about 2 minutes but might be outdated)
4. Exit"
    read -n1 answer
    echo ''
    if [ "$answer" == 1 ];then
      #switch to 64bit kernel
      
      echo "arm_64bit=1" | sudo tee --append /boot/config.txt >/dev/null
      echo -e "The 64-bit kernel has been enabled by adding 'arm_64bit=1' to /boot/config.txt\nPlease reboot and install the Wine app again."
      sleep infinity
    elif [ "$answer" == 2 ];then
      #compile 3g/1g kernel
      
      #backup ~/linux if it exists
      rm -rf ~/linux.bak
      [ -e ~/linux ] && (echo "$HOME/linux already exists, moving it to $HOME/linux.bak" ; mv -f ~/linux ~/linux.bak)
      
      #download kernel source code
      git clone --depth=1 https://github.com/raspberrypi/linux || error "Failed to git clone the raspberry pi kernel repo!"
      
      echo "Installing necessary build packages..."
      "${DIRECTORY}/pkg-install" "raspberrypi-kernel-headers build-essential bc git wget bison flex libssl-dev make libncurses-dev" "$(dirname "$0")" || error "Failed to install necessary packages to build kernel."
      
      #build for pi3
      cd ~/linux || error "Failed to enter the ~/linux folder!"
      KERNEL=kernel7
      make -j8 bcm2709_defconfig || error "The make command exited with failure. Full command: 'make -j8 bcm2709_defconfig'"
      
      #change memory split config
      echo "Setting memory split to 3G/1G"
      sed -i 's/CONFIG_VMSPLIT_2G=y/# CONFIG_VMSPLIT_2G is not set/g' ~/linux/.config || error "sed failed to edit $HOME/linux/.config file!"
      sed -i 's/# CONFIG_VMSPLIT_3G is not set/CONFIG_VMSPLIT_3G=1/g' ~/linux/.config
      
      echo '' | make -j8 zImage modules dtbs || error "Failed to make bcm2709_defconfig zImage modules dtbs!"
      
      #install
      echo "Copying new files to /boot/..."
      sudo make modules_install || error "sudo make modules_install failed!"
      sudo cp arch/arm/boot/dts/*.dtb /boot/ || error "Failed to copy dtb files to /boot!"
      sudo cp arch/arm/boot/dts/overlays/*.dtb* /boot/overlays/ || error "Failed to copy overlays to /boot/overlays!"
      sudo cp arch/arm/boot/dts/overlays/README /boot/overlays/
      sudo cp arch/arm/boot/zImage /boot/$KERNEL.img || error "Failed to copy kernel to /boot/$KERNEL.img!"
      cd
      rm -rf ~/linux
      
      echo "Removing the utilities that were used to compile the kernel..."
      "${DIRECTORY}/purge-installed" "$(dirname "$0")"
      
      #message
      echo -e "It appears the 3G/1G kernel has been built and installed successfully.\nPlease reboot and install the Wine app again."
      sleep infinity
    elif [ "$answer" == 3 ];then 
      #install precompiled 3g/1g kernel
      
      #backup ~/linux if it exists
      rm -rf ~/linux.bak
      [ -e ~/linux ] && (echo "$HOME/linux already exists, moving it to $HOME/linux.bak" ; mv -f ~/linux ~/linux.bak)
      #download precompiled kernel
      cd $HOME
      echo "Downloading precompiled kernel..."
      wget https://github.com/Itai-Nelken/RPi-3g-1g-kernel-wine/releases/download/5/rpi23_3g1g_kernel.zip -O ~/3g1g-rpi-kernel.zip || error "Failed to download prebuilt kernel!"
      #extract precompiled kernel
      echo "Extracting prebuilt kernel..."
      sleep 0.5 # so user has time to read what is happening
      unzip ~/3g1g-rpi-kernel.zip || error "Failed to extract kernel!"
      cd linux || error "Failed to change folder to ~/linux!"
      #install the precompiled kernel
      export KERNEL=kernel7
      sudo make modules_install || error "sudo make modules_install failed!"
      sudo cp arch/arm/boot/dts/*.dtb /boot/ || error "Failed to copy dtb files to /boot!"
      sudo cp arch/arm/boot/dts/overlays/*.dtb* /boot/overlays/ || error "Failed to copy overlays to /boot/overlays!"
      sudo cp arch/arm/boot/dts/overlays/README /boot/overlays/
      sudo cp arch/arm/boot/zImage /boot/$KERNEL.img || error "Failed to copy kernel to /boot/$KERNEL.img!"
      cd
      rm -rf linux ~/3g1g-rpi-kernel.zip
      #message
      echo -e "\e[1mIt appears the precompiled 3G/1G kernel has been installed successfully.\nPlease reboot and install the Wine app again.\e[0m"
      sleep infinity
    elif [ "$answer" == 4 ];then
      echo "User error: exited."
      exit 1
    else
      echo "Invalid response. Must be '1', '2', '3' or '4'."
    fi
  done
else
  echo "Your system is using a 3G/1G kernel. Continuing..."
fi

#Past this point, the pi is running a Wine-compatible kernel.

#install box86
"${DIRECTORY}/manage" install-if-not-installed Box86 || error "Box86 failed to install somehow!"

if ! command -v box86 >/dev/null ;then
  error "User error: Pi-Apps thinks Box86 is installed, however no command named 'box86' exists. Please install Box86 manually."
fi

pkill -9 wine
sudo apt purge -y wine &>/dev/null &

# Remove old wine, while leaving config intact
sudo rm -rf /usr/local/bin/wine /usr/local/bin/wineboot /usr/local/bin/wineserver /usr/local/bin/winecfg /usr/local/bin/winetricks ~/wine.tgz ~/wine ~/.cache/winetricks ~/.cache/wine 2>/dev/null

# Get dependencies
"${DIRECTORY}/pkg-install" "cabextract" "$(dirname "$0")" || exit 1

# Download
wget https://twisteros.com/wine.tgz -O ~/wine.tgz || error 'Failed to download wine!'
tar zxf ~/wine.tgz || error 'Failed to extract wine!'
rm ~/wine.tgz

[ ! -f ~/wine/bin/wine ] && error "the wine.tgz extraction succeeded, but the file '$HOME/wine/bin/wine' is missing!"

# Install
#sudo ln -s ~/wine/bin/wine /usr/local/bin/wine
sudo ln -s ~/wine/bin/winecfg /usr/local/bin/winecfg
sudo ln -s ~/wine/bin/wineserver /usr/local/bin/wineserver
sudo ln -s ~/wine/bin/wineboot /usr/local/bin/wineboot

echo "#!/bin/bash
setarch linux32 -L $HOME/wine/bin/wine"' "$@"' | sudo tee /usr/local/bin/wine >/dev/null
sudo chmod +x /usr/local/bin/wine /usr/local/bin/wineboot /usr/local/bin/wineserver /usr/local/bin/winecfg

sudo wget https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks -O /usr/local/bin/winetricks || error "Failed to download winetricks!"
sudo chmod +x /usr/local/bin/winetricks


#create menu button to winecfg
echo "[Desktop Entry]
StartupNotify=true
Terminal=false
Type=Application
Name=Wine Configuration
Exec=wine winecfg
Icon=$(dirname "$0")/icon-64.png
Categories=System;
Comment=Configure wine" > ~/.local/share/applications/wine-config.desktop

echo "[Desktop Entry]
Name=Winetricks
Comment=Work around problems and install applications under Wine
Exec=bash -c 'BOX86_NOBANNER=1 box86 winetricks --gui'
Terminal=false
Icon=$(dirname "$0")/icon-64.png
Type=Application
Categories=System;" > ~/.local/share/applications/wine-tricks.desktop

echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Wine Desktop
Comment=Wine graphical desktop environment to mimic a Windows OS
Icon=$(dirname "$0")/icon-64.png
Exec=wine explorer /desktop=shell,1280x720
Terminal=false
Categories=System;" > ~/.local/share/applications/wine-explorer.desktop

echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Wine Program Manager
Comment=Install/Remove Windows programs
Icon=$(dirname "$0")/icon-64.png
Exec=wine uninstaller
Terminal=false
Categories=System;" > ~/.local/share/applications/wine-uninstaller.desktop

echo "[Desktop Entry]
Version=1.0
Type=Application
Name=Wine Task Manager
Comment=View running processes within Wine
Icon=$(dirname "$0")/icon-64.png
Exec=wine taskmgr
Terminal=false
Categories=System;" > ~/.local/share/applications/wine-taskmgr.desktop

# Boot wine (make fresh wineprefix in ~/.wine
BOX86_NOBANNER=1
setarch linux32 -L box86 ~/wine/bin/wine wineboot

#wait until above process exits
while [ ! -z "$(pgrep -i 'wine C:')" ];do
  sleep 1
done
echo "First wineboot finished. Now updating wine prefix..."

#update the wine prefix (~/.wine) to fix the issue that causes wine to not know its system drive
#running as background process - terminal will exit but that's ok
setsid wine wineboot -u

exit 0
